<template>
  <div class="setting_child">
    <van-form @submit="onsubmit()">
      <van-nav-bar :left-text="leftText"
                   left-arrow
                   @click-left="onClickLeft"
      >
        <template #right>
          <van-button type="primary"
                      size="mini"
                      :disabled="isDisabled"
                      native-type="submit"
                      color="#7232DD"
          >
            修改
          </van-button>
        </template>
      </van-nav-bar>
      <van-field v-model="value" :rules="[{pattern, message: message}]"/>
    </van-form>
  </div>
</template>

<script>
import {NavBar, Button, Form} from "vant";
import {Field} from "vant";
import {Toast} from "vant";
import {changeNickName, changePhone} from "@/api/user";

export default {
  name: "SettingUserPhone",
  components: {
    [NavBar.name]: NavBar,
    [Button.name]: Button,
    [Field.name]: Field,
    [Form.name]: Form,
    Toast,
  },
  data() {
    return {
      leftText: "",
      defaultValue: "",
      value: "",
      isDisabled: true,
      pattern: "",
      message: ""
    }
  },
  created() {
    const pageTag = this.$route.params.name;
    this.defaultValue = this.$route.params.default;
    this.value = this.$route.params.default;
    if (pageTag === "nickName") {
      this.leftText = "更改名称";

    } else if (pageTag === "userPhone") {
      this.leftText = "更改电话号码";
      this.pattern = /^1[3|4|5|7|8]\d{9}$/;
      this.message = "请输入正确的手机号码"
    }
  },
  beforeUpdate() {
    this.isDisabled = false
  },
  methods: {
    // 路由跳转
    onClickLeft() {
      this.$router.go(-1);
    },
    // 修改用户信息
    onsubmit() {
      Toast.loading({
        message: '保存中...',
        forbidClick: true,
      });
      if (this.$route.params.name === "nickName") {
        changeNickName({nickName: this.value})
          .then(() => {
            return this.$store.dispatch("user/getInfo")
          })
          .then(res => {
            Toast.success("修改成功");
            this.$router.go(-1);
          })
          .catch(err => {
            Toast.fail("修改失败");
          })
      } else if (this.$route.params.name === "userPhone") {
        changePhone({phone: this.value})
          .then(() => {
            return this.$store.dispatch("user/getInfo")
          })
          .then(res => {
            Toast.success("修改成功");
            this.$router.go(-1);
          })
          .catch(err => {
            Toast.fail("修改失败");
          })
      }

    },
  }
}
</script>

<style scoped>
.setting_child {
  background-color: rgb(247, 246, 251);
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
</style>
